package com.luck.easyfoodbatch.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.igexin.sdk.PushManager;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.DemoHelper;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.db.DemoDBManager;
import com.luck.easyfoodbatch.ease.EaseCommonUtils;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.mine.LoginModel;
import com.luck.easyfoodbatch.mvp.mine.LoginPresenter;
import com.luck.easyfoodbatch.mvp.mine.LoginView;
import com.luck.easyfoodbatch.mvp.model.UserModel;
import com.luck.easyfoodbatch.service.MessageService;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements LoginView {
    private static final String TAG = "LoginActivity";
    @BindView(R.id.login_icon)
    ImageView loginIcon;
    @BindView(R.id.et_tel)
    EditText etTel;
    @BindView(R.id.ll_del)
    LinearLayout llDel;
    @BindView(R.id.rl_username)
    RelativeLayout rlUsername;
    @BindView(R.id.et_psw)
    EditText etPsw;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    private LoginModel loginModel;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("action.app.refresh.login")) {
                finish();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login, "登录", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        PushManager.getInstance().initialize(this);
        registerReceiver(receiver, "action.app.refresh.login");
        etTel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    llDel.setVisibility(View.VISIBLE);
                } else {
                    llDel.setVisibility(View.GONE);
                }
            }
        });
        String mobile = (String) SharedPreferencesUtil.getData(this, "mobile", "");
        if (!Tools.isNull(mobile)) {
            etTel.setText(mobile);
        }
    }

    @OnClick({R.id.ll_del, R.id.btn_login, R.id.tv_register, R.id.tv_forget})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_del:
                etTel.setText("");
                break;
            case R.id.btn_login:
                String phone = etTel.getText().toString().trim();
                String password = etPsw.getText().toString().trim();
                if (Tools.isNull(phone)) {
                    T.showToast(mContext, "请输入您的手机号");
                } else if (!Tools.validatePhone(phone)) {
                    T.showToast(mContext, "请输入正确手机号");
                } else if (Tools.isNull(password)) {
                    T.showToast(mContext, "请输入您的密码");
                } else {
                    showProgressDialog("正在登录，请稍候……");
                    // 环信登录成功，在登录本地
                    loginModel = new LoginPresenter(LoginActivity.this, mContext);
                    loginModel.appLogin(phone, password, PushManager.getInstance().getClientid(LoginActivity.this));
//                    loginModel.appLogin(phone, password);
                }
                break;
            case R.id.tv_register:
//                startAct(RegisterActivity.class);
                startAct(UserTypeActivity.class);
                break;
            case R.id.tv_forget:
                startAct(ForgetPasswordActivity.class);
                break;
        }
    }

    private List<Integer> roles = new ArrayList<>();// 权限标识

    @Override
    public void loginSuccess(UserModel userModel) {
        if (userModel != null) {
            if (userModel.getStatus() == HttpUtil.RESULT_OK) {
                User data = userModel.getData();
                if (data != null) {
                    String role = data.getRole();
                    //role = 0 或者 =1再去登录环信
                    roles.clear();
                    String[] split = role.split(",");
                    for (String code : split) {
                        if (!Tools.isNull(code)) {
                            roles.add(Integer.parseInt(code));
                        }
                    }
                    if (roles.size() > 1) {
                        if (roles.contains(1)) {
                            loginHX(userModel);
                        } else {
                            data.setAuthToken(userModel.getAuthToken());
                            App.getInstance().saveObject(data, HttpUtil.USER_KEY);
                            SharedPreferencesUtil.saveData(LoginActivity.this, "mobile", data.getMobile());
                            // 消息Service进行本地消息同步
                            startService(new Intent(LoginActivity.this, MessageService.class));
                            sendBroadcast("action.app.refresh.mine");
                            sendBroadcast("action.app.cart.refresh");
                            finish();
                        }
                    } else {
                        if (roles.contains(0) || roles.contains(1)) {
                            loginHX(userModel);
                        } else {
                            data.setAuthToken(userModel.getAuthToken());
                            App.getInstance().saveObject(data, HttpUtil.USER_KEY);
                            SharedPreferencesUtil.saveData(LoginActivity.this, "mobile", data.getMobile());
                            // 消息Service进行本地消息同步
                            startService(new Intent(LoginActivity.this, MessageService.class));
                            sendBroadcast("action.app.refresh.mine");
                            sendBroadcast("action.app.cart.refresh");
                            finish();
                        }
                    }
                } else {
                    hideShowProgress();
                }

            } else {
                hideShowProgress();
                T.showToast(mContext, userModel.getMsg());
            }
        } else {
            hideShowProgress();
        }
    }

    /**
     * 登录环信
     */
    public void loginHX(final UserModel userModel) {
        final User data = userModel.getData();
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(data.getMobile_hx())) {
            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(data.getPassword())) {
            Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(data.getMobile_hx());

        final long start = System.currentTimeMillis();
        // call login method
        Log.d(TAG, "EMClient.getInstance().login");
        EMClient.getInstance().login(data.getMobile_hx(), "ysp123456", new EMCallBack() {

            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideShowProgress();
                    }
                });
                Log.d(TAG, "login: onSuccess");
                EMClient.getInstance().chatManager().loadAllConversations();
                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().updateCurrentUserNick(
                        App.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }
                data.setAuthToken(userModel.getAuthToken());
                App.getInstance().saveObject(data, HttpUtil.USER_KEY);
                SharedPreferencesUtil.saveData(LoginActivity.this, "mobile", data.getMobile());
                // 消息Service进行本地消息同步
                startService(new Intent(LoginActivity.this, MessageService.class));
                sendBroadcast("action.app.refresh.mine");
                sendBroadcast("action.app.cart.refresh");
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d(TAG, "login: onProgress");
            }

            @Override
            public void onError(final int code, final String message) {
                Log.d(TAG, "login: onError: " + code);
                runOnUiThread(new Runnable() {
                    public void run() {
                        hideShowProgress();
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    public void httpStatusError() {
        T.showToast(mContext, getResources().getString(R.string.app_http_error));
    }

    @Override
    public void hideLoading() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
